extends Control
class_name VirtualJoystick

## 摇杆设置
@export var deadzone: float = 0.1  # 死区，避免微小移动
@export var max_distance: float = 25.0  # 摇杆最大拖拽距离（背景半径40，摇杆头半径15，所以最大距离是25）

## 信号
signal joystick_moved(direction: Vector2)
signal joystick_released()

## 私有变量
var is_dragging: bool = false
var joystick_center: Vector2
var joystick_knob: Control
var joystick_background: Control

func _ready():
	# 获取摇杆组件
	joystick_background = $Background
	joystick_knob = $Background/Knob
	
	# 记录摇杆中心位置
	joystick_center = joystick_background.position + joystick_background.size / 2
	
	# 创建圆形纹理
	create_circular_textures()
	
	# 设置摇杆初始位置（确保摇杆头居中）
	_reset_joystick()
	
	# 调试信息
	print("=== 摇杆初始化调试信息 ===")
	print("摇杆名称: ", name)
	print("摇杆左上角的绝对坐标: ", global_position)
	print("摇杆中心的绝对坐标: ", global_position + size / 2)
	print("Background中心的绝对坐标: ", global_position + joystick_background.position + joystick_background.size / 2)
	print("摇杆大小: ", size)
	print("Background位置: ", joystick_background.position)
	print("Background大小: ", joystick_background.size)
	print("==========================")

func _input(event):
	# 处理鼠标事件（在PC上模拟触摸）
	if event is InputEventMouseButton:
		_handle_mouse_button(event)
	elif event is InputEventMouseMotion:
		_handle_mouse_motion(event)
	# 处理触摸事件（在移动设备上）
	elif event is InputEventScreenTouch:
		_handle_touch(event)
	elif event is InputEventScreenDrag:
		_handle_drag(event)
	elif event is InputEventKey:
		_handle_keyboard_simulation(event)

func _handle_touch(event: InputEventScreenTouch):
	if event.pressed:
		# 检查触摸是否在摇杆区域内
		var touch_pos = event.position
		# 使用视觉摇杆的实际中心位置
		var center = joystick_background.position + joystick_background.size / 2
		var distance = touch_pos.distance_to(center)
		
		# 输出详细的调试信息
		print("=== 摇杆触摸调试信息 ===")
		print("摇杆名称: ", name)
		print("点击的绝对坐标: ", event.position)
		print("实际摇杆中心的绝对坐标: ", global_position + size / 2)
		print("视觉摇杆中心的绝对坐标: ", global_position + joystick_background.position + joystick_background.size / 2)
		print("========================")
		
		# 如果触摸在背景圆圈范围内，则激活摇杆
		if distance <= 40:  # 背景圆圈半径
			is_dragging = true
			_update_joystick_position(touch_pos)
			print("摇杆触摸开始: ", name, " 位置: ", touch_pos, " 距离中心: ", distance)
			# 阻止事件传播，避免触发其他UI
			get_viewport().set_input_as_handled()
	else:
		# 释放触摸
		if is_dragging:
			_reset_joystick()
			joystick_released.emit()
			print("摇杆触摸结束: ", name)
			# 阻止事件传播
			get_viewport().set_input_as_handled()

func _handle_drag(event: InputEventScreenDrag):
	if is_dragging:
		var touch_pos = event.position
		_update_joystick_position(touch_pos)
		# 阻止事件传播
		get_viewport().set_input_as_handled()

func _update_joystick_position(touch_pos: Vector2):
	# 计算相对于背景圆圈中心的方向和距离
	# 使用视觉摇杆的实际中心位置
	var background_center = joystick_background.position + joystick_background.size / 2
	var direction = touch_pos - background_center
	var distance = direction.length()
	
	# 限制拖拽距离（确保摇杆头不会超出背景圆圈）
	if distance > max_distance:
		direction = direction.normalized() * max_distance
		distance = max_distance
	
	# 更新摇杆位置（由于Knob设置了居中锚点，position就是相对于中心的偏移）
	joystick_knob.position = direction
	
	# 输出摇杆移动后的绝对坐标
	print("摇杆移动后的绝对坐标:")
	print("  实际摇杆的绝对坐标: ", global_position + size / 2)
	print("  视觉摇杆的绝对坐标: ", global_position + joystick_background.position + joystick_background.size / 2)
	print("  摇杆头的绝对坐标: ", global_position + joystick_background.position + joystick_knob.position + joystick_knob.size / 2)
	
	# 计算输出方向（考虑死区）
	var output_direction = Vector2.ZERO
	if distance > deadzone * max_distance:
		output_direction = direction.normalized()
	
	# 发送摇杆移动信号
	joystick_moved.emit(output_direction)

func _reset_joystick():
	is_dragging = false
	# 重置摇杆头到背景圆圈中心位置（由于Knob已经设置了居中锚点，只需要重置偏移）
	joystick_knob.position = Vector2.ZERO

func get_direction() -> Vector2:
	if is_dragging:
		# 由于Knob设置了居中锚点，position就是相对于中心的偏移
		var direction = joystick_knob.position
		var distance = direction.length()
		
		if distance > deadzone * max_distance:
			return direction.normalized()
	
	return Vector2.ZERO

func is_active() -> bool:
	return is_dragging

## 鼠标事件处理（PC模拟触摸）
func _handle_mouse_button(event: InputEventMouseButton):
	if event.button_index == MOUSE_BUTTON_LEFT:
		if event.pressed:
			# 检查鼠标是否在摇杆区域内
			var mouse_pos = get_local_mouse_position()
			# 使用视觉摇杆的实际中心位置
			var center = joystick_background.position + joystick_background.size / 2
			var distance = mouse_pos.distance_to(center)
			
			# 输出详细的调试信息
			print("=== 摇杆点击调试信息 ===")
			print("摇杆名称: ", name)
			print("点击的绝对坐标: ", get_global_mouse_position())
			print("实际摇杆中心的绝对坐标: ", global_position + size / 2)
			print("视觉摇杆中心的绝对坐标: ", global_position + joystick_background.position + joystick_background.size / 2)
			print("Background位置: ", joystick_background.position)
			print("Background大小: ", joystick_background.size)
			print("Background中心: ", joystick_background.position + joystick_background.size / 2)
			print("使用的检测中心: ", center)
			print("========================")
			
			# 如果鼠标在背景圆圈范围内，则激活摇杆
			if distance <= 40:  # 背景圆圈半径
				is_dragging = true
				_update_joystick_position(mouse_pos)
				print("鼠标摇杆开始: ", name, " 位置: ", mouse_pos, " 距离中心: ", distance)
				# 阻止事件传播
				get_viewport().set_input_as_handled()
		else:
			# 释放鼠标
			if is_dragging:
				_reset_joystick()
				joystick_released.emit()
				print("鼠标摇杆结束: ", name)
				# 阻止事件传播
				get_viewport().set_input_as_handled()

func _handle_mouse_motion(_event: InputEventMouseMotion):
	if is_dragging:
		var mouse_pos = get_local_mouse_position()
		_update_joystick_position(mouse_pos)
		# 阻止事件传播
		get_viewport().set_input_as_handled()

## 键盘模拟功能（用于测试）
func _handle_keyboard_simulation(event: InputEventKey):
	if not event.pressed:
		return
	
	# 检查是否是移动摇杆（通过名称判断）
	var is_move_joystick = name == "MoveJoystick"
	var is_attack_joystick = name == "AttackJoystick"
	
	if is_move_joystick:
		# 移动摇杆键盘模拟
		match event.keycode:
			KEY_1:  # 数字1键激活移动摇杆
				_simulate_joystick_activation()
			KEY_2:  # 数字2键模拟向上移动
				_simulate_joystick_direction(Vector2.UP)
			KEY_3:  # 数字3键模拟向下移动
				_simulate_joystick_direction(Vector2.DOWN)
			KEY_4:  # 数字4键模拟向左移动
				_simulate_joystick_direction(Vector2.LEFT)
			KEY_5:  # 数字5键模拟向右移动
				_simulate_joystick_direction(Vector2.RIGHT)
			KEY_0:  # 数字0键释放移动摇杆
				_simulate_joystick_release()
	
	elif is_attack_joystick:
		# 攻击摇杆键盘模拟（使用不同按键避免冲突）
		match event.keycode:
			KEY_Q:  # Q键激活攻击摇杆
				_simulate_joystick_activation()
			KEY_I:  # I键模拟向上攻击
				_simulate_joystick_direction(Vector2.UP)
			KEY_K:  # K键模拟向下攻击
				_simulate_joystick_direction(Vector2.DOWN)
			KEY_J:  # J键模拟向左攻击
				_simulate_joystick_direction(Vector2.LEFT)
			KEY_L:  # L键模拟向右攻击
				_simulate_joystick_direction(Vector2.RIGHT)
			KEY_U:  # U键释放攻击摇杆
				_simulate_joystick_release()

func _simulate_joystick_activation():
	is_dragging = true
	print("键盘模拟激活摇杆: ", name)

func _simulate_joystick_direction(direction: Vector2):
	if is_dragging:
		# 模拟摇杆移动到指定方向
		var background_center = joystick_background.position + joystick_background.size / 2
		var simulated_pos = background_center + direction * max_distance
		_update_joystick_position(simulated_pos)
		print("键盘模拟摇杆方向: ", direction, " (", name, ")")

func _simulate_joystick_release():
	if is_dragging:
		_reset_joystick()
		joystick_released.emit()
		print("键盘模拟释放摇杆: ", name)

## 创建圆形纹理
func create_circular_textures():
	# 创建背景圆形纹理
	var background_sprite = $Background/BackgroundCircle
	if background_sprite:
		var bg_texture = ImageTexture.new()
		var bg_image = Image.create(80, 80, false, Image.FORMAT_RGBA8)
		draw_circle_on_image(bg_image, Color(0.3, 0.3, 0.3, 0.5), Vector2(40, 40), 40)
		bg_texture.set_image(bg_image)
		background_sprite.texture = bg_texture
	
	# 创建摇杆头圆形纹理
	var knob_sprite = $Background/Knob/KnobCircle
	if knob_sprite:
		var knob_texture = ImageTexture.new()
		var knob_image = Image.create(30, 30, false, Image.FORMAT_RGBA8)
		
		# 根据摇杆类型设置颜色
		var knob_color = Color(0.8, 0.8, 0.8, 0.8)  # 默认白色
		if name == "AttackJoystick":
			knob_color = Color(0.8, 0.2, 0.2, 0.8)  # 攻击摇杆用红色
		
		draw_circle_on_image(knob_image, knob_color, Vector2(15, 15), 15)
		knob_texture.set_image(knob_image)
		knob_sprite.texture = knob_texture

## 在图像上绘制圆形
func draw_circle_on_image(image: Image, color: Color, center: Vector2, radius: float):
	for x in range(image.get_width()):
		for y in range(image.get_height()):
			var pixel_pos = Vector2(x, y)
			var distance = center.distance_to(pixel_pos)
			
			if distance <= radius:
				image.set_pixel(x, y, color)
